package com.tech.koufu.ui.view;

import java.io.ByteArrayInputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.android.volley.AuthFailureError;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.Request.Method;
import com.android.volley.Response.ErrorListener;
import com.android.volley.Response.Listener;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.tech.koufu.MainActivity;
import com.tech.koufu.MyApplication;
import com.tech.koufu.R;
import com.tech.koufu.action.PullStockParser;
import com.tech.koufu.model.CompetitionGroup;
import com.tech.koufu.model.StockInfo;
import com.tech.koufu.model.UserStocks;
import com.tech.koufu.tools.CookieStringRequest;
import com.tech.koufu.tools.KouFuTools;
import com.tech.koufu.tools.Statics;
import com.tech.koufu.ui.activity.BuyStocksActivity;
import com.tech.koufu.ui.activity.SellStocksListActivity;
import com.tech.koufu.ui.adapter.MarketAdapter;
import com.tech.koufu.ui.adapter.StocksGridItemAdapter;
import com.umeng.analytics.MobclickAgent;

import extras.com.handmark.pulltorefresh.library.PullToRefreshBase;
import extras.com.handmark.pulltorefresh.library.PullToRefreshGridView;
import extras.com.handmark.pulltorefresh.library.PullToRefreshBase.OnRefreshListener2;
import android.app.Application;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.GridView;
import android.widget.Toast;

/**
 * 自选股票Grid
 * 
 * @author jl_luo
 * 
 */
public class GridStocksFragment extends Fragment {
	private static final String TAG = "GridStocksFragment";
	private Context mContext;
	private View rootView;
	private PullToRefreshGridView mPullToRefreshGridView;
	private GridView actualGridView;
	private StocksGridItemAdapter mAdapter;
	private ArrayList<Map<String, String>> map;
	StringRequest stringRequest;
	private RequestQueue mQueue;
	private String ncode, name, code;
	private ArrayList<StockInfo> datas;
	private Handler mHandler;
	private ArrayList<UserStocks> mUserStocks;
	private int page = 1;
	CookieStringRequest cookieStringRequest;
	private MyApplication myApp;
	private StringBuilder codeBuilder;

	public static GridStocksFragment newInstance(int tabid,
			ArrayList<UserStocks> userStocks) {
		GridStocksFragment array = new GridStocksFragment();
		Bundle args = new Bundle();
		args.putInt("tabid", tabid);
		args.putSerializable("userStocks", userStocks);
		array.setArguments(args);
		return array;
	}

	@Override
	public View onCreateView(LayoutInflater inflater,
			@Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
		Log.d(TAG, "~~~~onCreateView~~~~~~~tabid="
				+ getArguments().get("tabid"));
		if (rootView == null) {
			rootView = inflater
					.inflate(R.layout.fragment_choose_viewpager_stocks,
							container, false);
			mContext = this.getActivity();
			initView();
			initHandler();
			initData();
		}
		ViewGroup parent = (ViewGroup) rootView.getParent();
		if (parent != null) {
			parent.removeView(rootView);
		}
		return rootView;
	}
	
	public void onResume() {
	    super.onResume();
	    MobclickAgent.onResume(mContext);       //统计时长
	}
	public void onPause() {
	    super.onPause();
	    MobclickAgent.onPause(mContext);
	}
	
	private void initView() {
		myApp = (MyApplication) getActivity().getApplication();
		mPullToRefreshGridView = (PullToRefreshGridView) rootView
				.findViewById(R.id.gv_scs); 
		actualGridView = mPullToRefreshGridView.getRefreshableView();
		mPullToRefreshGridView.setOnRefreshListener(new OnRefreshListener2() {

			@Override
			public void onPullDownToRefresh(PullToRefreshBase refreshView) {
				mPullToRefreshGridView.onRefreshComplete();
			}

			@Override
			public void onPullUpToRefresh(PullToRefreshBase refreshView) {
				mPullToRefreshGridView.onRefreshComplete();
			}
		});
		actualGridView.setOnItemClickListener(itemClick);
	}

	private void initHandler() {
		mHandler = new Handler() {
			@Override
			public void handleMessage(Message msg) {
				super.handleMessage(msg);
			}
		};
	}

	private OnItemClickListener itemClick = new OnItemClickListener() {

		@Override
		public void onItemClick(AdapterView<?> parent, View view, int position,
				long id) {
			Intent intent = new Intent(getActivity(), BuyStocksActivity.class);
			intent.putExtra("stockInfo", datas.get(position));
			intent.putExtra("datatype", 1);
			intent.putExtra("parsetype", 1);
			startActivity(intent);
			getActivity().finish();
			
		}
	};

	@Override
	public void onActivityCreated(@Nullable Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);
		Log.d(TAG, "~~~~onActivityCreated~~~~~~~");
	}

	private void initData() {
		mUserStocks = (ArrayList<UserStocks>) getArguments().getSerializable(
				"userStocks");
		mQueue = Volley.newRequestQueue(getActivity().getApplicationContext());
		datas = new ArrayList<StockInfo>();
		mAdapter = new StocksGridItemAdapter(getActivity()
				.getApplicationContext(), datas);
		actualGridView.setAdapter(mAdapter);
		codeBuilder = new StringBuilder();
		initDefData();
	}

	private void initDefData(){ 
		if(mUserStocks!=null && mUserStocks.size()>0){ 
			for(UserStocks userStocks:mUserStocks){
				codeBuilder.append(userStocks.getStockId()).append(",");
			}
			ncode = codeBuilder.toString();
		}	 
		loadData();
		loadZxg();
	}
	
	public void searchLoad() {
		Bundle bundle = getArguments();
		String key = bundle.getString("key");
		code = bundle.getString("code");
		name = bundle.getString("name");
		ncode = bundle.getString("ncode");
		loadData();
	}

	public void loadData() {
		if(ncode==null)
			return;
		datas.clear();
		String url = Statics.URL_2 + Statics.URL_BinStock + ncode
				+ "&field=ZG,ZD,ZX,ZSP";
		Log.v(TAG, "URL_BinStock="+url);
		stringRequest = new StringRequest(url, new Response.Listener<String>() {
			@Override
			public void onResponse(String response) {
				try {
					Log.v(TAG, "URL_BinStock="+response);
					if(response!=null){
						String[] rs = response.split(";");
						for(String results : rs){
							String[] result = results.split(",");
							StockInfo stockInfo = new StockInfo();
							stockInfo.setName(result[1].trim());
							stockInfo.setCode(result[0].trim());
							stockInfo.setZg(result[2].trim());
							stockInfo.setZd(result[3].trim());
							stockInfo.setZx(result[4].trim());
							stockInfo.setZsp(result[5].trim());
							datas.add(stockInfo);
						}
					} 
					mAdapter.notifyDataSetChanged();
				} catch (Exception e) {
					e.printStackTrace();
				}

			}
		}, new Response.ErrorListener() {
			@Override
			public void onErrorResponse(VolleyError error) {
				Log.e("TAG", error.getMessage(), error);
			}
		});
		stringRequest.setCharset("GBK");
		mQueue.add(stringRequest);
	}

	@Override
	public void onStop() {
		super.onStop();
		clear();
	}
	
	private void loadZxg(){
		codeBuilder = new StringBuilder(); 
		String url = Statics.URL_PHP+Statics.IF_myZixuangu;
		cookieStringRequest = new CookieStringRequest(Method.POST, url, new Listener<String>() {

			@Override
			public void onResponse(String response) { 
				Log.w(TAG, response);
				if(!TextUtils.isEmpty(response)){
					try {  
						JSONObject obj = new JSONObject(response);
						String status = obj.optString("status");
						if(status.equals("0")){
							JSONArray arry = obj.optJSONArray("data");
							if(arry!=null && arry.length()>0){
								int length = arry.length();
								for(int i=0;i<length;i++){
									JSONObject stock = arry.getJSONObject(i); 
									codeBuilder.append(KouFuTools.getEnCode(
											stock.optString("stock_code"))).append(","); 
								}
								ncode = codeBuilder.toString();
							}else{
								page--;
							}
						}else{
							page--; 
						}
					} catch (JSONException e) { 
						e.printStackTrace();
					}
				} 
				mPullToRefreshGridView.onRefreshComplete();
				 
			}
		}, new ErrorListener() {

			@Override
			public void onErrorResponse(VolleyError error) { 
				Log.e(TAG, error.getMessage());
				error.printStackTrace();
			}
		}){
			@Override
			protected Map<String, String> getParams() throws AuthFailureError { 
				Map<String, String> params = new HashMap<String, String>();
				params.put("page", page+"");    
				params.put("userid",myApp.getUserid()); 
				return params;
			}
		};  
		cookieStringRequest.setHeader(myApp.phpsessid);
		mQueue.add(cookieStringRequest);
	}

	/**
	 * 
	 * @Title: clear
	 * @Description: TODO(清楚缓存)
	 * @param 设定文件
	 * @return void 返回类型
	 * @throws
	 */
	private void clear() {
		if (map != null) {
			map.clear();
		}
		if (stringRequest != null)
			mQueue.cancelAll(stringRequest);
		if(cookieStringRequest!= null){
			mQueue.cancelAll(cookieStringRequest);
		}
	}
}
